package com.jungle.bfi.generator;

import com.jungle.bfi.generator.mo.AttributeMo;
import com.jungle.bfi.generator.mo.ModelMo;
import com.jungle.bfi.generator.util.PathUtil;
import com.thoughtworks.qdox.JavaProjectBuilder;
import com.thoughtworks.qdox.model.JavaClass;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;

public class ModelLoader {
    public JavaClass load(File javaFile, String className) throws IOException {
        JavaProjectBuilder builder = new JavaProjectBuilder();
        builder.addSource(javaFile);
        return builder.getClassByName(className);
    }

    public ModelMo loadModel(File javaFile, String className) throws IOException {
        JavaClass javaClass = load(javaFile, className);
        return toClassInfo(javaClass);
    }

    private static ModelMo toClassInfo(JavaClass javaClass) {
        ModelMo modelMo = new ModelMo();
        modelMo.setName(javaClass.getName());
        modelMo.setModel(javaClass.getName().replace("Po", ""));
        modelMo.setComment(javaClass.getComment());

        // 获取属性信息
        javaClass.getFields().stream().map(field -> {
            AttributeMo attributeMo = new AttributeMo();
            attributeMo.setName(field.getName());
            attributeMo.setComment(field.getComment());
            attributeMo.setType(field.getType().getName());
            return attributeMo;
        }).forEach(modelMo::addField);

        // 获取导入信息
        javaClass.getSource().getImports().stream().filter(
                        item -> !item.startsWith("jakarta.persistence") && !item.startsWith("java.lang"))
                .forEach(modelMo::addImport);

        return modelMo;
    }

    public static void main(String[] args) {
        try {
            String className = "VoucherTypePo";
            String packageName = "com.jungle.bfi.entity";
            ModelMo modelMo = ModelLoader.load(packageName + "." + className);

            System.out.println(modelMo);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static ModelMo load(String fullClassName) throws IOException {
        // 获取项目路径
        Path projectPath = PathUtil.getProjectPath();
        // 获取模块路径
        Path modulePath = projectPath.getParent().resolve("main");
        // 获取java源路径
        Path javaPath = modulePath.resolve("src/main/java");
        // 获取完整类文件路径
        //String fullClassName = packageName + "." + className;
        // 获取java文件路径
        String javaName = fullClassName.replace(".", "/").concat(".java");
        // 拼装java文件完整
        Path javaFilePath = javaPath.resolve(javaName);
        // 获取java文件对象
        File javaFile = javaFilePath.toFile();

        ModelLoader loader = new ModelLoader();
        // 加载类信息
        return loader.loadModel(javaFile, fullClassName);
    }

}
